package com.example.sqllite;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Fragment3 extends Fragment {
    public Fragment3(){
            super(R.layout.fragment3);
    }

    public void onViewCreated(@NonNull View view, @Nullable Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);

        EditText nameEditText = getView().findViewById(R.id.username);
        EditText numEditText = getView().findViewById(R.id.password);
        Button Btn = getView().findViewById(R.id.button);
        String FILE_NAME = "STORED3";

        SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        String name = settings.getString("name", "");
        String num = settings.getString("num", "");
        nameEditText.setText(name);
        numEditText.setText(num);

        Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                String password = numEditText.getText().toString();
                editor.putString("name", nameEditText.getText().toString());
                editor.putString("num", getSHA256StrJava(password));
                editor.commit();
                Toast.makeText(getActivity(), "保存成功!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static String getSHA256StrJava(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
